package com.oauth.service.generic.dao;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.stereotype.Repository;

import com.oauth.service.generic.beans.OAuthServiceBean;
import com.oauth.service.generic.constants.OAuthTokenState;
import com.oauth.service.jdosupport.PersistenceFactory;

@Repository
public class OAuthDAOImpl implements OAuthDAO {

	public void deleteToken(Long memberId, Long applicationId) {
		OAuthServiceBean serviceBean = getToken(memberId, applicationId);

		if (serviceBean != null) {

			serviceBean.setState(OAuthTokenState.DELETED);
			Date currentDate = new Date();
			serviceBean.setLastUpdateDate(currentDate);
			PersistenceManager persistenceManager = PersistenceFactory.get()
					.getPersistenceManager();
			try {
				persistenceManager.makePersistent(serviceBean);
			} finally {
				persistenceManager.close();
			}
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public OAuthServiceBean getToken(Long memberId, Long applicationId) {
		PersistenceManager persistenceManager = PersistenceFactory.get().getPersistenceManager();

		Query query = persistenceManager.newQuery(OAuthServiceBean.class, "memberId == " + memberId
				+ " && applicationId == " + applicationId + " && state == stateParam");

		query.declareParameters("int stateParam");
		List<OAuthServiceBean> results = (List<OAuthServiceBean>) query
				.execute(OAuthTokenState.ACTIVE.getState());

		if (results != null && !results.isEmpty()) {
			return results.get(0);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public List<OAuthServiceBean> getAllTokens(Long memberId) {
		PersistenceManager persistenceManager = PersistenceFactory.get().getPersistenceManager();

		Query query = persistenceManager.newQuery(OAuthServiceBean.class, "memberId == " + memberId
				+ " && state == stateParam");

		query.declareParameters("int stateParam");

		List<OAuthServiceBean> results = (List<OAuthServiceBean>) query
				.execute(OAuthTokenState.ACTIVE.getState());
		return results;
	}

	@Override
	public OAuthServiceBean persistToken(OAuthServiceBean pServiceBean) {

		OAuthServiceBean serviceBean = getToken(pServiceBean.getMemberId(),
				pServiceBean.getApplicationId());

		if (serviceBean != null) {
			// Update key so that it will update existing object instead of
			// creating new one.
			pServiceBean.setKey(serviceBean.getKey());
		}
		// default set to active.
		pServiceBean.setState(OAuthTokenState.ACTIVE);

		if (pServiceBean.getCreationDate() == null) {
			pServiceBean.setCreationDate(new Date());
		}

		pServiceBean.setLastUpdateDate(new Date());

		PersistenceManager persistenceManager = PersistenceFactory.get().getPersistenceManager();
		try {
			pServiceBean = persistenceManager.makePersistent(pServiceBean);
		} finally {
			persistenceManager.close();
		}
		return pServiceBean;
	}

}
